package com.my.study.atomic;

import sun.misc.Unsafe;

/**
 * @author Carlos
 * @version 1.0
 * @Description 自定义原子整数线程安全操作类
 * @date 2021/6/4 22:06
 **/
public class AtomicData {
    private volatile int data;
    static final Unsafe UNSAFE;
    static final long DATA_OFFSET;

    static {
        UNSAFE = UnsafeAccessor.getUnsafe();
        Class<AtomicData> adClass = AtomicData.class;
        try {
            DATA_OFFSET = UNSAFE.objectFieldOffset
                    (adClass.getDeclaredField("data"));
        } catch (NoSuchFieldException e) {
            throw new Error(e);
        }
    }

    public final int get() {
        return this.data;
    }

    public final boolean compareAndSet(int expect, int update) {
        return UNSAFE.compareAndSwapInt(this, DATA_OFFSET, expect, update);
    }

    public final void decrement(int amount) {
        int prev, next;
        do {
            prev = get();
            next = prev - amount;
        } while (!compareAndSet(prev, next));
    }


}
